﻿using AutoMapper;
using Microsoft.EntityFrameworkCore;
using QMERP.Domain.Dtos;
using QMERP.Domain.Entities;
using QMERP.Domain.Enums;
using QMERP.Infrastructure.EFCore;
using QMERP.Infrastructure.EFCore.Extensions;
using QMERP.Infrastructure.Extensions;
using QMERP.Infrastructure.Security;

namespace QMERP.Application.Services
{
    public class SystemService : ISystemService
    {
        private readonly IUserService _userSvc;
        private readonly IAppService _appSvc;
        private readonly IPrivilegeService _privilegeSvc;
        private readonly ICurrentUser _currentUser;
        private readonly QMERPDbContext _db;
        private readonly IMapper _mapper;
        public SystemService(IPrivilegeService privilegeSvc, IAppService appSvc, IUserService userSvc, ICurrentUser currentUser, QMERPDbContext db, IMapper mapper)
        {
            _privilegeSvc = privilegeSvc;
            _appSvc = appSvc;
            _userSvc = userSvc;
            _currentUser = currentUser;
            _db = db;
            _mapper = mapper;
        }
        /// <summary>
        /// 初始化系统
        /// </summary>
        /// <returns></returns>
        public async Task<SystemResponse> Init()
        {
            List<App> apps;
            string[] types = { AppTypeEnum.Catalog.ToString(), AppTypeEnum.App.ToString() };
            if (_currentUser.IsAdmin)
            {
                apps = await _db.App.GetBasicApps(types).OrderBy(o => o.Sort).ToListAsync();
            }
            else
            {
                var privileges = await _privilegeSvc.GetCurrentUserPrivileges();
                var appIds = privileges.Where(x => x.Access == AccessEnum.App.ToString()).Select(s => s.AccessValue).ToList();
                apps = await _db.App.GetBasicApps(types).Where(x => appIds.Contains(x.Id)).OrderBy(o => o.Sort).ToListAsync();
            }
            SystemResponse system = new()
            {
                UserInfo = await _userSvc.CurrentUser(),
                Apps = _mapper.Map<List<RouterResponse>>(apps),
                Licenses = await _privilegeSvc.GetCurrentUserLicenses()
            };
            return system;
        }
    }
}
